/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.edgent.connectors.command.runtime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.apache.edgent.function.Supplier;

/**
 * A {@code Supplier<Iterable<String>>} for ingesting a process's output.
 * <P>
 * The iterator returned by {@link Iterable#iterator()} returns
 * {@code hasNext()==true} until a read from {@link Process#getInputStream()}
 * returns EOF or an IOError.
 */
class ProcessReader implements Supplier<Iterable<String>> {
  private static final long serialVersionUID = 1L;
  private final BufferedReader reader;
  
  /**
   * Create a new supplier of UTF8 strings read from a process's
   * {@link Process#getInputStream() output}.
   * 
   * @param process the process to read from.
   */
  ProcessReader(Process process) {
    reader = new BufferedReader(new InputStreamReader(
        process.getInputStream(), StandardCharsets.UTF_8));
  }

  @Override
  public Iterable<String> get() {
    return new Iterable<String>() {

      @Override
      public Iterator<String> iterator() {
        return new Iterator<String>() {
          private Boolean hasNext = null;
          private String next = null;
          
          @Override
          public boolean hasNext() {
            if (hasNext != null)
              return hasNext;
            next = getNext();
            hasNext = next != null;
            return hasNext;
          }

          @Override
          public String next() {
            if (next == null)
              throw new NoSuchElementException();
            hasNext = null;
            return next;
          }
          
        };
      }
      
    };
  }

  /**
   * Get the next available line from the process's stdout
   * @return null if no more input (or error)
   */
  private String getNext() {
    try {
      return reader.readLine();
    } catch (IOException e) {
      CommandConnector.logger.error("Unable to readline from cmd", e);
      return null;
    }
  }
  
}